import base64
import os
import traceback

import requests
from flask import current_app
from rapidocr import RapidOCR

engine = RapidOCR()


def local_ocr(image_path):
    """
    使用本地OCR API识别图片文件，针对交管12123学法减分内容优化

    参数:
        image_path: 图片文件路径

    返回:
        包含识别结果的字典，如果识别失败则返回None
    """
    global engine
    try:
        result = engine(image_path).txts
        full_text_list = []
        if not result:
            current_app.logger.info(f"OCR结果为空: {result}")
            return {'raw_text': ''}

        for item in result:
            full_text_list.append(item)
        # 过滤掉"下一题"等导航文本
        end_word = "".join(full_text_list).replace('下一题', '').replace('我的答题', '')
        current_app.logger.info(f"本地OCR识别结果: {end_word}")

        return {
            'raw_text': end_word
        }

    except Exception as e:
        current_app.logger.info(f"本地OCR处理异常: {str(e)}")
        current_app.logger.error("".join(traceback.format_exc()))
        return None


def baidu_ocr(image_path):
    """
    使用百度OCR API识别图片文件

    参数:
        image_path: 图片文件路径

    返回:
        包含识别结果的字典，如果识别失败则返回None
    """
    try:
        API_KEY = os.environ.get('BAIDU_OCR_API_KEY')
        SECRET_KEY = os.environ.get('BAIDU_OCR_SECRET_KEY')

        # 获取access_token
        def get_access_token():
            url = f"https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={API_KEY}&client_secret={SECRET_KEY}"
            response = requests.post(url)
            result = response.json()
            if 'access_token' in result:
                return result['access_token']
            else:
                current_app.logger.error(f"获取百度OCR access_token失败: {result}")
                return None

        # 调用通用文字识别API
        def ocr_api_call(image_path):
            access_token = get_access_token()
            if not access_token:
                return None

            request_url = f"https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token={access_token}"

            # 二进制方式打开图片文件
            with open(image_path, 'rb') as f:
                img = base64.b64encode(f.read())

            # 构建请求参数
            headers = {'Content-Type': 'application/x-www-form-urlencoded'}
            params = {"image": img}

            response = requests.post(request_url, data=params, headers=headers)
            return response.json()

        # 调用百度OCR API识别文本
        current_app.logger.error("调用百度OCR API...")
        ocr_result = ocr_api_call(image_path)

        if not ocr_result or 'error_code' in ocr_result:
            current_app.logger.error(f"百度OCR API返回错误: {ocr_result}")
            return None

        full_text_list = []
        words_results = ocr_result['words_result']
        for i, item in enumerate(words_results):
            full_text_list.append(item['words'])
        # 拼接成一个完整的文本
        full_text = " ".join(full_text_list) or " ".join(ocr_result)
        if not full_text:
            current_app.logger.error("未识别到任何文本")
            return None

        current_app.logger.error(f"OCR识别成功， {full_text}")

        if full_text == 'words_result words_result_num log_id':
            current_app.logger.error("未识别到任何文本")
            return None

        extracted_question = {'raw_text': full_text}

        return extracted_question

    except Exception as e:
        current_app.logger.error(f"百度OCR处理异常: {str(e)}")
        current_app.logger.error("".join(traceback.format_exc()))
        return None


def recognize_image(image_path):
    """图像识别处理入口"""
    # 先调用本地ocr
    try:
        local_result = local_ocr(image_path)
        if local_result:
            return local_result
        return baidu_ocr(image_path)
    except Exception as e:
        current_app.logger.error(f"图像识别异常: {str(e)}")
        current_app.logger.error("".join(traceback.format_exc()))
        return None